package com.sunchangpeng.wechat.mp.stat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.sunchangpeng.wechat.mp.EndpointProvider;
import com.sunchangpeng.wechat.mp.MpAppSetting;
import com.sunchangpeng.wechat.mp.MpWechatClientFactory;
import lombok.Data;

import java.time.LocalDate;
import java.util.List;

public class InterfaceStats extends Stats {
    public static InterfaceStats with(MpAppSetting appSetting) {
        InterfaceStats stats = new InterfaceStats();
        stats.setWechatClient(MpWechatClientFactory.getInstance().with(appSetting));
        return stats;
    }

    /**
     * 获取接口分析数据
     */
    List<InterfaceSummary> getInterfaceSummary(LocalDate start, LocalDate end) {
        if (diffThanDays(start, end, 30)) {
            throw new IllegalArgumentException("start和end相差不能超过30天以上");
        }

        String url = EndpointProvider.get("url.stats.interface.summary");
        return JSON.parseObject(doRequest(url, start, end), InterfaceSummaryWrapper.class).getList();
    }

    /**
     * 获取接口分析分时数据
     */
    List<InterfaceSummary> getInterfaceSummaryHour(LocalDate day) {
        String url = EndpointProvider.get("url.stats.interface.summaryhour");
        return JSON.parseObject(doRequest(url, day, day), InterfaceSummaryWrapper.class).getList();
    }

    @Data
    public static class InterfaceSummaryWrapper {
        private List<InterfaceSummary> list;
    }


    @Data
    public static class InterfaceSummary {
        @JSONField(name = "ref_date")
        private String refDate;

        @JSONField(name = "ref_hour")
        private Integer refHour;

        @JSONField(name = "callback_count")
        private Integer callbackCount;

        @JSONField(name = "fail_count")
        private Integer failCount;

        @JSONField(name = "total_time_cost")
        private Integer totalTimeCost;

        @JSONField(name = "max_time_cost")
        private Integer maxTimeCost;
    }
}
